{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from sklearn import datasets, linear_model,discriminant_analysis,cross_validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 加载数据方法，这里使用scikit-learn自带的糖尿病病人的数据集\n",
    "def load_data():\n",
    "    diabetes = datasets.load_diabetes()\n",
    "    return cross_validation.train_test_split(diabetes.data, diabetes.target,test_size=0.25,random_state=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 线性回归模型\n",
    "def test_LinearRegression(*data):\n",
    "    train_x,test_x, train_y, test_y = data\n",
    "    regr = linear_model.LinearRegression()\n",
    "    regr.fit(train_x, train_y)\n",
    "    \n",
    "    # y=wx+b  分别显示权重及b值\n",
    "    print('【权重】coefficient:{0}'.format(regr.coef_))\n",
    "    print('【b值】intercept: {0}'.format(regr.intercept_))\n",
    "    # 均方差\n",
    "    print('【均方差】residual sum of squares:{0}'.format(np.mean((regr.predict(test_x) -test_y)**2)))\n",
    "    # 成绩\n",
    "    print('【成绩】Testing Score: {0}'.format(regr.score(test_x,test_y)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "【权重】coefficient:[ -43.26774487 -208.67053951  593.39797213  302.89814903 -560.27689824\n",
      "  261.47657106   -8.83343952  135.93715156  703.22658427   28.34844354]\n",
      "【b值】intercept: 153.06798218266258\n",
      "【均方差】residual sum of squares:3180.1988368427287\n",
      "【成绩】Testing Score: 0.3594009098971551\n"
     ]
    }
   ],
   "source": [
    "# 用糖尿病数据进行测试\n",
    "train_x,test_x, train_y, test_y = load_data()\n",
    "test_LinearRegression(train_x, test_x, train_y, test_y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
